const Router = require('koa-router')
const Redis = require('koa-redis')
const nodeMailer = require('nodemailer')
const User = require('../dbs/models/users.js')
const Email = require('../dbs/config.js')
const Passport = require('./utils/passport.js')
const axios = require('./utils/axios.js')


let router = new Router({
  prefix: '/users'
})

let Store = new Redis().client

// 注册接口
router.post('/signup', async (ctx) => {
  const {
    username,
    password,
    email,
    code
  } = ctx.request.body

  // 验证验证码是否有效
  if(code) {
    const saveCode = await Store.hget(`nodemail:${username}`, 'code')
    const saveExpire = await Store.hget(`nodemail:${username}`, 'expire')
    if(code === saveCode) {
      if(new Date().getTime() > saveExpire) {
        ctx.body = {
          code: -1,
          msg: '验证码已过期，请重新尝试'
        }
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '请填写正确的验证码'
      }
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '请填写验证码'
    }
  }

  // 验证用户名是否存在
  let user = await User.find({
    username
  })
  if(user.length) {
    console.log('用户名已被注册')
    return ctx.response.body = {
      code: -1,
      msg: '用户名已被注册'
    }
  } else {
    // 创建用户
    let nuser = await User.create({
      username,
      password,
      email
    })
    if(nuser) {
      let res = await axios.post('/users/signin', { username, password })
      if(res.data && res.data.code === 0) {
        ctx.body = {
          code: 0,
          msg: '注册成功',
          user: res.data.user
        }
      } else {
        ctx.body = {
          code: -1,
          msg: res.data.msg,
        }
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '注册失败',
      }
    }
  }
})

// 登录接口
router.post('/signin', async (ctx, next) => {
  return Passport.authenticate('local', function(err, user, info, status) {
    if (err) {
      ctx.body = {
        code: -1,
        msg: err
      }
    } else {
      if (user) {
        ctx.body = {
          code: 0,
          msg: '登录成功',
          user
        }
        return ctx.login(user)
      } else {
        ctx.body = {
          code: 1,
          msg: info
        }
      }
    }
  })(ctx, next)
})

// 获取验证码
router.post('/verify', async (ctx, next) => {
  let username = ctx.request.body.username
  const saveExpire = await Store.hget(`nodemail:${username}`, 'expire')
  if(saveExpire && new Date().getTime() < saveExpire) {
    ctx.body = {
      code: -1,
      msg: '请求过于频繁，1分钟内一次有效'
    }
  }

  // 第三方发送邮件API信息
  let transporter = nodeMailer.createTransport({
    host: Email.smtp.host,
    port: 587,
    secure: false,
    auth: {
      user: Email.smtp.user,
      pass: Email.smtp.pass
    }
  })

  // 绑定验证码和过期时间
  let ko = {
    code: Email.smtp.code(),
    expire: Email.smtp.expire(),
    email: ctx.request.body.email,
    user: ctx.request.body.username,
  }

  // 邮件内容
  let mailOptions = {
    from: `"认证邮件" <${Email.smtp.user}>`,
    to: ko.email,
    subject: '《高仿美团》注册码',
    html: `您正在高仿美团APP中进行注册操作，您的邀请码是${ko.code}，非本人操作请无视`
  }

  // 发出邮件
  await transporter.sendMail(mailOptions, (error, info) => {
    if(error) {
      return console.log('error')
    } else {
      Store.hmset(
        `nodemail:${ko.user}`, 
        'code', ko.code, 
        'expire', ko.expire, 
        'email', ko.email
      )
    }
  })

  ctx.body = {
    code: 0,
    msg: '验证码已发送，可能会延迟收到，有效期一分钟'
  }
})

// 退出接口
router.get('/exit', async (ctx, next) => {
  await ctx.logout()
  if(!ctx.isAuthenticated()) {
    ctx.body = {
      code: 0
    }
  } else {
    ctx.body = {
      code: -1
    }
  }
})

// 获取用户信息
router.get('/getUser', async (ctx) => {
  if(ctx.isAuthenticated()) {
    const { username, email } = ctx.session.passport.user
    ctx.body = {
      username,
      email
    }
  } else {
    ctx.body = {
      username: '',
      email: ''
    }
  }
})

module.exports = router
